package net.chrone.quickpayapi.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {
	
	/**
     * 正常日期格式化模板.
     */
    private static final SimpleDateFormat NORMAL_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final SimpleDateFormat NORMAL_DATE_FORMAT_YY_MM_DD = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat NORMAL_DATE_FORMAT_YY_MM_DD_ = new SimpleDateFormat("yyyyMMdd");

    private static final SimpleDateFormat NORMAL_DATE_FORMAT_YYMMDDHHMISS = new SimpleDateFormat("yyyyMMddHHmmss");
	
	public static Date string2date(String timeStr,String pattern){
		try {
			return new SimpleDateFormat(pattern).parse(timeStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
    /**
     * 取得当前日期的String�?
     * @return String 返回值为日期,格式自定义，�?��符合标准，参考Java Doc “SimpleDateFormat�?
     */
    public static String getCurrentDate(String aFormat) {
        String tDate = new SimpleDateFormat(aFormat).format(new java.util.Date(System.currentTimeMillis()));
        return tDate;
    }
    
    public static String getCurrentDate() {
        return DateUtils.getCurrentDate("yyyyMMdd");
    }
    public static String getCurrentDateTime() {
        return DateUtils.getCurrentDate("yyyyMMddHHmmss");
    }
    
    public static String getNewRandomCode(int codeLen) {
		//首先定义随机数据�?
		//根据�?��得到的数据码的长度返回随机字符串
		java.util.Random randomCode = new java.util.Random();
		String strCode = "";
		while (codeLen > 0) {
			int charCode=randomCode.nextInt(9);
			strCode += charCode;
			codeLen--;
		}
		return strCode;
	}
    
    /**
	 * 取得两个时间段的时间间隔
	 * 
	 * @author color
	 * @param t1
	 *            时间1
	 * @param t2
	 *            时间2
	 * @return t2 与t1的间隔天�?
	 * @throws ParseException
	 *             如果输入的日期格式不�?000-00-00 格式抛出异常
	 */
	public static int getBetweenDays(String t1, String t2) {
		DateFormat format = new SimpleDateFormat("yyyyMMdd");
		int betweenDays = 0;
		Date d1 = null;
		Date d2 = null;
		try {
			d1 = format.parse(t1);
			d2 = format.parse(t2);
		} catch (ParseException e) {
			return -1;
		}
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(d1);
		c2.setTime(d2);
		// 保证第二个时间一定大于第�?��时间
		if (c1.after(c2)) {
			c1 = c2;
			c2.setTime(d1);
		}
		int betweenYears = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
		betweenDays = c2.get(Calendar.DAY_OF_YEAR)
				- c1.get(Calendar.DAY_OF_YEAR);
		for (int i = 0; i < betweenYears; i++) {
			c1.set(Calendar.YEAR, (c1.get(Calendar.YEAR) + 1));
			betweenDays += c1.getMaximum(Calendar.DAY_OF_YEAR);
		}
		return betweenDays;
	}
	
	/**
	 *  获取跨度时间
	 * @param date 当前时间
	 * @param addArray 时间偏移量数组 field,amount
	 * @return
	 */
	public static Date addTime(Date date,int field,int amount) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(field, amount);
		return calendar.getTime();
	}
	
	public static String formatDate(Date date,String aFormat){
		SimpleDateFormat sdf=new SimpleDateFormat(aFormat);
		return sdf.format(date);
	}
	
	public static Date parseDate(String dateStr,String aFormat){
		SimpleDateFormat sdf=new SimpleDateFormat(aFormat);
		try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
	}
	
	/**
	 * 获取距今日前N天的日期
	 */
	public static Date getLastDays(int days) {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DATE, Integer.parseInt("-" + days));
		return c.getTime();
	}
	
	/**
     * 获取月份
     */
    public static Date getCalcMonths(int month) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, month);
        return c.getTime();
    }
	
	/**
	 * 获取日期月份差
	 * @param start yyyyMMdd
	 * @param end yyyyMMdd
	 * @return 相差月份数
	 */
	public static int getDateMonthBetween(String start, String end) {
		SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
		Date d_start = null;
		Date d_end = null;
		try {
			d_start = formater.parse(start);
			d_end = formater.parse(end);
		} catch (ParseException e) {
			throw new IllegalArgumentException("参数格式有误：期望-yyyyMMdd，实际-" + start + "," + end);
		}
		Calendar c_start = Calendar.getInstance();
		Calendar c_end = (Calendar) c_start.clone();
		c_start.setTime(d_start);
		c_end.setTime(d_end);
		int y_start = c_start.get(Calendar.YEAR);
		int m_start = c_start.get(Calendar.MONTH);
		
		int y_end = c_end.get(Calendar.YEAR);
		int m_end = c_end.get(Calendar.MONTH);
		
		int t_month_s = y_start * 12 + m_start;
		int t_month_e = y_end * 12 + m_end;
		int temp = t_month_e - t_month_s;
		int result = temp;
		int day_start = c_start.get(Calendar.DAY_OF_MONTH);
		int day_end = c_end.get(Calendar.DAY_OF_MONTH);
		
		if(day_start > day_end){
			result = temp -1;
		}
		return result;
	}
	
	public static String wrapMonth(int m) {
		if(m >= 10){
			return m + "";
		}else{
			return "0" + m;
		}
	}
	
	/**
	 * 获取日期间有几个月份(最大为5,最小为2)
	 * @param start
	 * @param end
	 * @return
	 */
	public static String[] getMonthBetween(String start, String end) {
		String[] months = new String[5];
		int between = 3;//最多相差三月
		if(getDateMonthBetween(start, end) > between){
			return months;
		}
		String year_start = start.substring(0, 4);
		String year_end = end.substring(0, 4);
		String month_start = start.substring(4, 6);
		String month_end = end.substring(4, 6);
		int y_start = Integer.parseInt(year_start);
		int y_end = Integer.parseInt(year_end);
		int m_start = Integer.parseInt(month_start);
		int m_end = Integer.parseInt(month_end);
		//先获取上个月份
		int m_last = m_start - 1;
		m_last = m_last == 0 ? 12 : m_last;
		months[0] = wrapMonth(m_last);
		int temp = m_start;
		for (int i = 1; i < months.length; i++) {
			
			months[i] = wrapMonth(temp);
			//开始月份增加至等于结束月份
			temp++;
			if(temp > 12){
				temp = temp > 12 ? 1 : temp;
				y_start++;
			}
			if((y_start == y_end && temp > m_end) || (y_start > y_end && temp < m_end))
				break;
		}
		return months;
	}
	
	/**
	 * 获取配置时间类型
	 * @param timeout
	 * @return
	 */
	public static int getFieldByConfig(String timeout){
		if(timeout.endsWith("s")||timeout.endsWith("S")){//秒
			return Calendar.SECOND;
		}else if(timeout.endsWith("m")||timeout.endsWith("M")){//分
			return Calendar.MINUTE;
		}else if(timeout.endsWith("h")||timeout.endsWith("H")){//小时
			return Calendar.HOUR_OF_DAY;
		}else if(timeout.endsWith("d")||timeout.endsWith("D")){//天
			return Calendar.DAY_OF_MONTH;
		}
		return -1;
	}
	
	
	/**
     * 正常日期格式化.
     * 
     * @param date
     *            日期距离1970年1月1日秒数
     * @return 格式化后的日期(2011-11-24)
     */
    public static String dateFormatYYMMDD(long date) {
        return NORMAL_DATE_FORMAT_YY_MM_DD.format(new Date(date * 1000));
    }

    /**
     * 正常日期格式化.
     * 
     * @param date
     *            日期距离1970年1月1日秒数
     * @return 格式化后的日期(20111124)
     */

    public static String getCurrentDateStr() {
        return NORMAL_DATE_FORMAT_YY_MM_DD_.format(new Date());
    }

    public static String getCurrentDateYYYYMMDDStr() {
        return NORMAL_DATE_FORMAT_YY_MM_DD.format(new Date());
    }

    public static String getNextDayYYYYMMDDStr() {
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(NORMAL_DATE_FORMAT_YY_MM_DD.parse(getCurrentTime()));
            cal.add(Calendar.DATE, 1);
            return NORMAL_DATE_FORMAT_YY_MM_DD.format(cal.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static long getNextDayYYYYMMDDLong() {
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(NORMAL_DATE_FORMAT_YY_MM_DD.parse(getCurrentTime()));
            cal.add(Calendar.DATE, 1);
            return cal.getTimeInMillis();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0l;
    }

    /**
     * 正常日期格式化.
     * 
     * @param date
     *            日期距离1970年1月1日秒数
     * @return 格式化后的日期(2011-11-24 16:46:38)
     */
    public static String dateFormat(long date) {
        return NORMAL_DATE_FORMAT.format(new Date(date * 1000));
    }

    /**
     * 正常日期格式化.
     *
     * @param date
     *            日期距离1970年1月1日秒数
     * @return 格式化后的日期(2011-11-24)
     */
    public static String dateFormatYYYYMMDD(long date) {
        return NORMAL_DATE_FORMAT_YY_MM_DD.format(new Date(date * 1000));
    }

    /**
     * 正常日期格式化.
     * 
     * @param date
     *            日期距离1970年1月1日秒数
     * @return 格式化后的日期(2011-11-24 16:46:38)
     */

    public static String dateFormat(Date date) {
        return NORMAL_DATE_FORMAT.format(date);
    }

    /**
     * 正常日期格式化.
     * 
     * @param date
     *            日期距离1970年1月1日秒数
     * @return 格式化后的日期(20111124164638)
     */

    public static String dateFormathhmmss(Date date) {
        return NORMAL_DATE_FORMAT_YYMMDDHHMISS.format(date);
    }

    /**
     * 正常日期格式化.
     * 
     * @param date
     *            日期距离1970年1月1日秒数
     * @return 格式化后的日期(20111124164638)
     */

    public static String dateFormatYYYYMMDD(Date date) {
        return NORMAL_DATE_FORMAT_YY_MM_DD_.format(date);
    }

    /**
     * 正常日期格式化.
     * 
     * @param date
     *            日期距离1970年1月1日秒数
     * @return 格式化后的日期(2011-11-24 16:46:38)
     */

    public static String getCurrentTime() {
        return NORMAL_DATE_FORMAT_YY_MM_DD.format(new Date());
    }

    /**
     * 获取当前距1970年1月1日秒数.
     * 
     * @return 当前距1970年1月1日秒数.
     */
    public static long getTime() {
        return new Date().getTime() / 1000;
    }

    /**
     * 获取当前距1970年1月1日秒数.
     * 
     * @return 获取最近一周的秒数.
     */
    public static long getLastWeekTime() {
        return new Date().getTime() / 1000 - 7 * 24 * 60 * 60;
    }

    /**
     * 获取当前距1970年1月1日秒数.
     * 
     * @return 获取最近一个月的秒数.
     */
    public static long getLastMonthTime() {
        return new Date().getTime() / 1000 - 30 * 24 * 60 * 60;
    }

    /**
     * 获取某年某月第一天.
     * 
     * @return 日期格式如：2011-12-31 00:00:00 .
     */
    public static long getFirstDayOfMonth(String year, String month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, Integer.valueOf(year));
        cal.set(Calendar.MONTH, Integer.valueOf(month) - 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
        return parseDate(NORMAL_DATE_FORMAT_YY_MM_DD.format(cal.getTime()) + " 00:00:00").getTime() / 1000;
    }

    /**
     * 获取某年某月最后一天.
     * 
     * @return 日期格式如：2011-12-31 23:59:59 .
     */
    public static long getLastDayOfMonth(String year, String month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, Integer.valueOf(year));
        cal.set(Calendar.MONTH, Integer.valueOf(month) - 1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        int value = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        cal.set(Calendar.DAY_OF_MONTH, value);
        return parseDate(NORMAL_DATE_FORMAT_YY_MM_DD.format(cal.getTime()) + " 23:59:59").getTime() / 1000;
    }

    /**
     * 解析字符串为Date.
     * 
     * @param dateString
     *            日期字符串 例如 2011-12-17 17:41:18.843 CST.
     * @return 解析后的日期类型.若解析出错则返回null
     */
    public static Date parseDate(String dateStr) {
        try {
            return NORMAL_DATE_FORMAT.parse(dateStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 解析字符串为Date.
     * 
     * @param dateString
     *            日期字符串 例如 2011-12-17 17:41:18.843 CST.
     * @return 解析后的日期类型.若解析出错则返回null
     */
    public static Date parseDateYYYYMMDDHHMMSS(String dateStr) {
        try {
            return NORMAL_DATE_FORMAT_YYMMDDHHMISS.parse(dateStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 正常日期格式化.
     * 
     * @param date
     *            日期距离1970年1月1日秒数
     * @return 格式化后的日期()
     */

    public static long parseLong(String date) {
        return parseDate(date).getTime() / 1000;
    }

    /**
     * 日期格式转换为字符串格式
     * 
     * @param date
     * @return 格式化后的日期字符串
     */
    public static String parseString(Date date) {

        return NORMAL_DATE_FORMAT_YY_MM_DD.format(date);
    }

    public static long getLastDayStartTime(long daytime) {
        Calendar todayStart = Calendar.getInstance();
        todayStart.setTimeInMillis(daytime * 1000);
        todayStart.add(Calendar.DAY_OF_YEAR, -1);
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTimeInMillis() / 1000;
    }

    public static long getLastDayEndTime(long daytime) {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.setTimeInMillis(daytime * 1000);
        todayEnd.add(Calendar.DAY_OF_YEAR, -1);
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTimeInMillis() / 1000;
    }

    public static long getTime(long time) {
        Calendar timeCalendar = Calendar.getInstance();
        Calendar nowCalendar = Calendar.getInstance();
        timeCalendar.setTimeInMillis(time * 1000);
        timeCalendar.set(Calendar.HOUR_OF_DAY, nowCalendar.get(Calendar.HOUR_OF_DAY));
        timeCalendar.set(Calendar.MINUTE, nowCalendar.get(Calendar.MINUTE));
        timeCalendar.set(Calendar.SECOND, nowCalendar.get(Calendar.SECOND));
        timeCalendar.set(Calendar.MILLISECOND, nowCalendar.get(Calendar.MILLISECOND));
        return timeCalendar.getTimeInMillis() / 1000;
    }

    public static long getStartTime(long daytime) {
        Calendar todayStart = Calendar.getInstance();
        todayStart.setTimeInMillis(daytime * 1000);
        // todayStart.add(Calendar.DAY_OF_YEAR, -1);
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime().getTime() / 1000;
    }
    
    public static long getEndTime(long daytime) {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.setTimeInMillis(daytime * 1000);
        // todayEnd.add(Calendar.DAY_OF_YEAR, -1);
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTimeInMillis() / 1000;
    }
    
    public static Date getStartDate(Integer year,Integer month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, Integer.valueOf(year));
        cal.set(Calendar.MONTH, Integer.valueOf(month) - 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
        return parseDate(NORMAL_DATE_FORMAT_YY_MM_DD.format(cal.getTime()) + " 00:00:00");
    }

    /**
     * 比较俩日期是否是同一天
     * 
     * @param d1
     * @param d2
     * @return
     */
    public static boolean compareSameDate(Date d1, Date d2) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(d1);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(d2);
        boolean isSameYear = c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR);
        boolean isSameMonth = isSameYear && c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH);
        boolean isSameDate = isSameMonth && c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH);
        return isSameDate;
    }

    /**
     * 当月的第一天距1970年1月1日秒数.
     * 
     * @param date
     * @return long
     * @author mengxm
     */
    public static final long firstMonthDayTime() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return cal.getTime().getTime() / 1000;
    }

    /**
     * 根据指定格式解析时间
     * 
     * @param dateString
     * @param fmtString
     * @return Date
     * @author mengxm
     */
    public static final Date parse(String dateString, String fmtString) {
        Date date = null;
        try {
            DateFormat format = new SimpleDateFormat(fmtString);
            date = format.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /** 比较提现前后时间间隔秒数 */
    public static long getDatePoor(Date endDate, Date startDate) {

        // 获得两个时间的秒时间差异
        long diff = (endDate.getTime() - startDate.getTime()) / 1000;
        return diff;
    }

    /**
     * 当前时间加几天
     * 
     * @param day
     *            天数
     * @return
     */
    public static long currentDateAddDay(int day) {
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(NORMAL_DATE_FORMAT_YY_MM_DD.parse(getCurrentTime()));
            cal.add(Calendar.DATE, day); // add N days
            return cal.getTimeInMillis() / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0l;
    }

    public static long dateAddDay(long dateLong, int day) {
        Calendar cal = Calendar.getInstance();
        Date d = new Date(dateLong * 1000);
        cal.setTime(d);
        cal.add(Calendar.DATE, day);
        return cal.getTimeInMillis() / 1000;
    }
    
     /**  
     * 计算两个日期之间相差的天数  
     * @param smdate 较小的时间 
     * @param bdate  较大的时间 
     * @return 相差天数 
     * @throws ParseException  
     */    
    public static int daysBetween(Date smdate,Date bdate){    
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        long between_days = 0L;
        try {
            smdate=sdf.parse(sdf.format(smdate));
            bdate=sdf.parse(sdf.format(bdate));  
            Calendar cal = Calendar.getInstance();    
            cal.setTime(smdate);    
            long time1 = cal.getTimeInMillis();                 
            cal.setTime(bdate);    
            long time2 = cal.getTimeInMillis();         
            between_days=(time2-time1)/(1000*3600*24);
        } catch (ParseException e) {
            e.printStackTrace();
        }  
       return Integer.parseInt(String.valueOf(between_days));           
    } 
    
    /** 日期转换为自定义格式输出 */
    public static String DateToString(Date date, String formatType) {
        if (date == null) {
            return null;
        }
        if (formatType == null || "".equals(formatType)) {
            return null;
        }
        String dateStr = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(formatType);
            dateStr = sdf.format(date);
            return dateStr;
        } catch (Exception e) {
            return null;
        }
    }

    public static long getStartTimeCurrentDay() {
        Calendar todayStart = Calendar.getInstance();
        //todayStart.add(Calendar.DAY_OF_YEAR,  -1);
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime().getTime() / 1000;
    }

    public static long getEndTimeCurrentDay() {
        Calendar todayStart = Calendar.getInstance();
        //todayStart.add(Calendar.DAY_OF_YEAR,  -1);
        todayStart.set(Calendar.HOUR_OF_DAY, 23);
        todayStart.set(Calendar.MINUTE, 59);
        todayStart.set(Calendar.SECOND, 59);
        todayStart.set(Calendar.MILLISECOND, 59);
        return todayStart.getTime().getTime() / 1000;
    }
    
    /** 日期转换为自定义格式输出 */
    public static String fomatDate(Date date, String format) {
        if (date == null) { 
            return "";
        }
        if (format == null || "".equals(format)) {
            return "";
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(date);
        } catch (Exception e) {
            e.printStackTrace();
            return "";

        }
    }
    
    
    public static String getLastDayFmtYYYYMMDD() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.add(Calendar.DAY_OF_YEAR, -1);
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return NORMAL_DATE_FORMAT_YY_MM_DD_.format(todayStart.getTime());
    }
    
    /**
     * @Title: getDateFormat 
     * @Description: 日期格式化 yyyy-MM-dd
     * @param str
     * @return String
     */
    public static String getDateFormat(String str){
        return dateFormatYYMMDD(Long.parseLong(str));
    }
    
    /**
     * @Title: getTimeFormat 
     * @Description: 时间格式化 yyyy-MM-dd HH:mm:ss
     * @param str
     * @return String
     */
    public static String getTimeFormat(String str){
        return dateFormat(Long.parseLong(str));
    }
   
	
	
   
}
